<template>
  <div class="satellite-nav">
    <div class="nav-header">
      <h2>卫星项目导览</h2>
      <button class="add-project-btn" @click="addProject">+ 添加项目</button>
    </div>
    
    <div class="project-tree">
      <div v-if="loading" class="loading-container">
        <div class="loading-text">加载中...</div>
      </div>
      <div v-else-if="projects.length === 0" class="empty-container">
        <div class="empty-text">暂无项目数据</div>
      </div>
      <div v-else>
        <div v-for="project in projects" :key="project.id" class="project-item">
        <div class="project-folder" @click="toggleProject(project.id)">
          <span class="folder-icon">📁</span>
          <span class="project-name">{{ project.name }}</span>
          <div class="project-actions">
            <button class="action-btn add-btn" @click.stop="addGroup(project.id)">+</button>
            <button class="action-btn edit-btn" @click.stop="editProject(project.id)">✏️</button>
            <button class="action-btn delete-btn" @click.stop="deleteProject(project.id)">🗑️</button>
          </div>
        </div>
        
        <div v-if="project.expanded" class="group-list">
          <div v-for="group in project.groups" :key="group.id" class="group-item">
            <div class="group-folder" @click="toggleGroup(group.id)">
              <span class="folder-icon">📁</span>
              <span class="group-name">{{ group.name }}</span>
              <div class="group-actions">
                <button class="action-btn add-btn" @click.stop="addSatellite(group.id)">+</button>
                <button class="action-btn edit-btn" @click.stop="editGroup(group.id)">✏️</button>
                <button class="action-btn delete-btn" @click.stop="deleteGroup(group.id)">🗑️</button>
              </div>
            </div>
            
            <div v-if="group.expanded" class="satellite-list">
              <div v-for="satellite in group.satellites" :key="satellite.id" class="satellite-item">
                <span class="satellite-icon">📄</span>
                <span class="satellite-name">{{ satellite.name }}</span>
                <div class="satellite-actions">
                  <button class="action-btn edit-btn" @click="editSatellite(satellite.id)">✏️</button>
                  <button class="action-btn delete-btn" @click="deleteSatellite(satellite.id)">🗑️</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import config from '../config/index.js'

export default {
  name: 'SatelliteProjectNav',
  data() {
    return {
      projects: [],
      loading: false
    }
  },
  async mounted() {
    await this.loadProjects()
  },
  methods: {
    // 加载项目数据
    async loadProjects() {
      try {
        this.loading = true
        const response = await axios.get(`${config.API_BASE_URL}/api/projects/`)
        console.log('项目API响应:', response.data)
        
        // 检查响应数据结构并正确提取项目数组
        let projectsData = []
        if (response.data && response.data.success && Array.isArray(response.data.data)) {
          projectsData = response.data.data
        } else if (Array.isArray(response.data)) {
          projectsData = response.data
        } else {
          console.warn('项目API返回的数据格式不正确:', response.data)
          projectsData = []
        }
        
        this.projects = projectsData.map(project => ({
          ...project,
          expanded: false,
          groups: (project.groups || []).map(group => ({
            ...group,
            expanded: false
          }))
        }))
      } catch (error) {
        console.error('加载项目失败:', error)
        alert('加载项目失败，请检查网络连接')
      } finally {
        this.loading = false
      }
    },

    // 切换项目展开状态
    toggleProject(projectId) {
      const project = this.projects.find(p => p.id === projectId)
      if (project) {
        project.expanded = !project.expanded
      }
    },

    // 切换组展开状态
    toggleGroup(groupId) {
      for (const project of this.projects) {
        const group = project.groups.find(g => g.id === groupId)
        if (group) {
          group.expanded = !group.expanded
          break
        }
      }
    },

    // 添加项目
    async addProject() {
      const name = prompt('请输入项目名称:')
      if (!name || !name.trim()) return
      
      try {
        const response = await axios.post(`${config.API_BASE_URL}/api/projects/`, {
          name: name.trim(),
          description: ''
        })
        if (response.data.success) {
          // 直接添加新项目到本地数据
          const newProject = {
            id: response.data.data.id, // 使用后端返回的正确ID
            name: name.trim(),
            description: '',
            expanded: true, // 新添加的项目默认展开
            groups: []
          }
          this.projects.push(newProject)
        }
      } catch (error) {
        console.error('添加项目失败:', error)
        alert('添加项目失败')
      }
    },

    // 添加组
    async addGroup(projectId) {
      const name = prompt('请输入组名称:')
      if (!name || !name.trim()) return
      
      try {
        const response = await axios.post(`${config.API_BASE_URL}/api/groups/`, {
          name: name.trim(),
          project: projectId,
          description: ''
        })
        if (response.data.success) {
          // 找到对应的项目并添加新组
          const targetProject = this.projects.find(p => p.id === projectId)
          if (targetProject) {
            // 确保项目处于展开状态
            targetProject.expanded = true
            
            // 添加新组到本地数据
            const newGroup = {
              id: response.data.data.id, // 使用后端返回的正确ID
              name: name.trim(),
              project: projectId,
              description: '',
              expanded: true, // 新添加的组默认展开
              satellites: []
            }
            
            if (!targetProject.groups) {
              targetProject.groups = []
            }
            targetProject.groups.push(newGroup)
          } else {
            // 如果找不到对应项目，则重新加载数据
            await this.loadProjects()
          }
        }
      } catch (error) {
        console.error('添加组失败:', error)
        alert('添加组失败')
      }
    },

    // 添加卫星
    async addSatellite(groupId) {
      const satelliteName = prompt('请输入卫星名称:')
      if (!satelliteName || !satelliteName.trim()) return
      
      try {
        const response = await axios.post(`${config.API_BASE_URL}/api/satellites/`, {
          name: satelliteName.trim(),
          group: groupId,
          description: ''
        })
        if (response.data.success) {
          // 找到对应的组并添加新卫星
          let targetGroup = null
          let targetProject = null
          for (const project of this.projects) {
            const group = project.groups.find(g => g.id === groupId)
            if (group) {
              targetGroup = group
              targetProject = project
              break
            }
          }
          
          if (targetGroup && targetProject) {
            // 确保项目和组都处于展开状态
            targetProject.expanded = true
            targetGroup.expanded = true
            
            // 添加新卫星到本地数据
            const newSatellite = {
              id: response.data.data.id, // 使用后端返回的正确ID
              name: satelliteName.trim(),
              group: groupId,
              description: ''
            }
            
            if (!targetGroup.satellites) {
              targetGroup.satellites = []
            }
            targetGroup.satellites.push(newSatellite)
          } else {
            // 如果找不到对应组，则重新加载数据
            await this.loadProjects()
          }
        }
      } catch (error) {
        console.error('添加卫星失败:', error)
        alert('添加卫星失败')
      }
    },

    // 编辑项目
    async editProject(projectId) {
      const project = this.projects.find(p => p.id === projectId)
      if (!project) return
      
      const newName = prompt('请输入新的项目名称:', project.name)
      if (!newName || !newName.trim() || newName.trim() === project.name) return
      
      try {
        const response = await axios.put(`${config.API_BASE_URL}/api/projects/${projectId}/`, {
          name: newName.trim(),
          description: project.description || ''
        })
        if (response.data.success) {
          // 直接更新本地数据
          project.name = newName.trim()
        }
      } catch (error) {
        console.error('更新项目失败:', error)
        alert('更新项目失败')
      }
    },

    // 删除项目
    async deleteProject(projectId) {
      const project = this.projects.find(p => p.id === projectId)
      if (!project) return
      
      if (!confirm(`确定要删除项目 "${project.name}" 吗？这将同时删除该项目下的所有组和卫星。`)) return
      
      // 先从本地数组中移除项目（乐观更新）
      this.projects = this.projects.filter(p => p.id !== projectId)
      
      // 然后发送删除请求（不处理错误，因为界面已经更新）
      try {
        await axios.delete(`${config.API_BASE_URL}/api/projects/${projectId}/`)
      } catch (error) {
        // 静默处理错误，因为采用乐观更新策略
      }
    },

    // 编辑组
    async editGroup(groupId) {
      let group = null
      for (const project of this.projects) {
        group = project.groups.find(g => g.id === groupId)
        if (group) break
      }
      if (!group) return
      
      const newName = prompt('请输入新的组名称:', group.name)
      if (!newName || !newName.trim() || newName.trim() === group.name) return
      
      try {
        const response = await axios.put(`${config.API_BASE_URL}/api/groups/${groupId}/`, {
          name: newName.trim(),
          project: group.project || this.getProjectIdByGroupId(groupId),
          description: group.description || ''
        })
        if (response.data.success) {
          // 直接更新本地数据
          group.name = newName.trim()
        }
      } catch (error) {
        console.error('更新组失败:', error)
        alert('更新组失败')
      }
    },

    // 删除组
    async deleteGroup(groupId) {
      let group = null
      let parentProject = null
      for (const project of this.projects) {
        group = project.groups.find(g => g.id === groupId)
        if (group) {
          parentProject = project
          break
        }
      }
      if (!group || !parentProject) return
      
      if (!confirm(`确定要删除组 "${group.name}" 吗？这将同时删除该组下的所有卫星。`)) return
      
      // 先从本地数组中移除组（乐观更新）
      parentProject.groups = parentProject.groups.filter(g => g.id !== groupId)
      
      // 然后发送删除请求（不处理错误，因为界面已经更新）
      try {
        await axios.delete(`${config.API_BASE_URL}/api/groups/${groupId}/`)
      } catch (error) {
        // 静默处理错误，因为采用乐观更新策略
      }
    },

    // 编辑卫星
    async editSatellite(satelliteId) {
      let satellite = null
      let groupId = null
      for (const project of this.projects) {
        for (const group of project.groups) {
          satellite = group.satellites.find(s => s.id === satelliteId)
          if (satellite) {
            groupId = group.id
            break
          }
        }
        if (satellite) break
      }
      if (!satellite) return
      
      const newName = prompt('请输入新的卫星名称:', satellite.name)
      if (!newName || !newName.trim() || newName.trim() === satellite.name) return
      
      try {
        const response = await axios.put(`${config.API_BASE_URL}/api/satellites/${satelliteId}/`, {
          name: newName.trim(),
          group: groupId,
          description: satellite.description || ''
        })
        if (response.data.success) {
          // 直接更新本地数据
          satellite.name = newName.trim()
        }
      } catch (error) {
        console.error('更新卫星失败:', error)
        alert('更新卫星失败')
      }
    },

    // 删除卫星
    async deleteSatellite(satelliteId) {
      let satellite = null
      let parentGroup = null
      for (const project of this.projects) {
        for (const group of project.groups) {
          satellite = group.satellites.find(s => s.id === satelliteId)
          if (satellite) {
            parentGroup = group
            break
          }
        }
        if (satellite) break
      }
      if (!satellite || !parentGroup) return
      
      if (!confirm(`确定要删除卫星 "${satellite.name}" 吗？`)) return
      
      // 先从本地数组中移除卫星（乐观更新）
      parentGroup.satellites = parentGroup.satellites.filter(s => s.id !== satelliteId)
      
      // 然后发送删除请求（不处理错误，因为界面已经更新）
      try {
        await axios.delete(`${config.API_BASE_URL}/api/satellites/${satelliteId}/`)
      } catch (error) {
        // 静默处理错误，因为采用乐观更新策略
        // 如果真的需要确认删除状态，可以在这里重新获取数据
      }
    },

    // 辅助方法：根据组ID获取项目ID
    getProjectIdByGroupId(groupId) {
      for (const project of this.projects) {
        const group = project.groups.find(g => g.id === groupId)
        if (group) return project.id
      }
      return null
    }
  }
}
</script>

<style scoped>
.satellite-nav {
  width: 100%;
  height: 100%;
  background: #f8f9fa;
  border-right: 1px solid #e9ecef;
  overflow-y: auto;
}

.nav-header {
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.add-project-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.add-project-btn:hover {
  background: #218838;
}

.project-tree {
  padding: 8px;
}

.project-item {
  margin-bottom: 4px;
}

.project-folder {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.project-folder:hover {
  background: #e9ecef;
}

.folder-icon {
  margin-right: 8px;
  font-size: 14px;
}

.project-name {
  flex: 1;
  font-weight: 500;
  color: #333;
}

.project-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.project-folder:hover .project-actions {
  opacity: 1;
}

.action-btn {
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.add-btn {
  background: #007bff;
  color: white;
}

.edit-btn {
  background: #6c757d;
  color: white;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.action-btn:hover {
  opacity: 0.8;
}

.group-list {
  margin-left: 24px;
  border-left: 2px solid #e9ecef;
  padding-left: 12px;
}

.group-item {
  margin-bottom: 4px;
}

.group-folder {
  display: flex;
  align-items: center;
  padding: 6px 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.group-folder:hover {
  background: #f1f3f4;
}

.group-name {
  flex: 1;
  font-weight: 500;
  color: #444;
  font-size: 13px;
}

.group-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.group-folder:hover .group-actions {
  opacity: 1;
}

.satellite-list {
  margin-left: 24px;
  border-left: 2px solid #e9ecef;
  padding-left: 12px;
}

.satellite-item {
  display: flex;
  align-items: center;
  padding: 6px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.satellite-item:hover {
  background: #f1f3f4;
}

.satellite-icon {
  margin-right: 8px;
  font-size: 12px;
}

.satellite-name {
  flex: 1;
  color: #555;
  font-size: 14px;
}

.satellite-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.satellite-item:hover .satellite-actions {
  opacity: 1;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 20px;
}

.loading-text,
.empty-text {
  color: #666;
  font-size: 14px;
}

.loading-text {
  animation: pulse 1.5s ease-in-out infinite alternate;
}

@keyframes pulse {
  from {
    opacity: 0.6;
  }
  to {
    opacity: 1;
  }
}
</style>